#include "portManagement.h"
#include <string.h>

using namespace std;

void blockIP(string ipToBlock = "")
{
	string command = "iptables -I INPUT -s " + ipToBlock + " -j DROP";
	system(command.c_str());
	printf("Blocking:%s\n", ipToBlock.c_str());
}

void blockPort(string portToBlock = "", string device = "")
{
	string command = "iptables -P INPUT -j DROP -p tcp --destination-port " + portToBlock
		+ " -i " + device;
	system(command.c_str());
	command = "iptables -P OUTPUT -j DROP -p tcp --destination-port " + portToBlock
		+ " -i " + device;
	system(command.c_str());
	command = "iptables -P INPUT -j DROP -p udp --destination-port " + portToBlock
		+ " -i " + device;
	system(command.c_str());
	command = "iptables -P OUTPUT -j DROP -p udp --destination-port " + portToBlock
		+ " -i " + device;
	system(command.c_str());
	printf("Blocking:%s\n", portToBlock.c_str());
}

void setInPolicy(string policy = "ACCEPT")
{
	string command = "iptables -P INPUT " + policy;
	system(command.c_str());
}

void setOutPolicy(string policy = "ACCEPT")
{
	string command = "iptables -P OUTPUT "  + policy;
	system(command.c_str());
}

void setForwardPolicy(string policy = "ACCEPT")
{
	string command = "iptables -P FORWARD "  + policy;
	system(command.c_str());
}

void dropAll()
{
	printf("Blocking all packets.\n");
	setInPolicy("DROP");
	setOutPolicy("DROP");
	setForwardPolicy("DROP");
}

void acceptAll()
{
	printf("Accepting all packets.\n");
	setInPolicy("ACCEPT");
	setOutPolicy("ACCEPT");
	setForwardPolicy("ACCEPT");
}

void acceptIP(string ipToAccept)
{
	string command = "iptables -A INPUT -s " + ipToAccept + " -j ACCEPT";
	system(command.c_str());
	command = "iptables -A OUTPUT -d " + ipToAccept + " -j ACCEPT";
	system(command.c_str());
	command = "iptables -A FORWARD -s " + ipToAccept + " -j ACCEPT";
	system(command.c_str());
	command = "iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT";
	system(command.c_str());
	command = "iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT";
	system(command.c_str());
	command = "iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT";
	system(command.c_str());
}

void acceptPort(string portToAccept = "", string device = "")
{
	string command = "iptables -A INPUT -j ACCEPT -p tcp --destination-port " + portToAccept
		+ " -i " + device;
	system(command.c_str());
	command = "iptables -A INPUT -j ACCEPT -p udp --destination-port " + portToAccept
		+ " -i " + device;
	system(command.c_str());
	command = "iptables -A OUTPUT -j ACCEPT -p tcp --destination-port " + portToAccept;
	system(command.c_str());
	command = "iptables -A OUTPUT -j ACCEPT -p udp --destination-port " + portToAccept;
	system(command.c_str());
}

void flushIPTables()
{
	string command = "iptables -F";
	system(command.c_str());
}